var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  '/',
  '/image/svg2.svg'
];

self.addEventListener('install', event => {
  console.log('--->install')

  // cache a cat SVG
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      console.log('Opened cache', cache);
      return cache.addAll(urlsToCache);
    })
  );
  self.skipWaiting()
});

self.addEventListener('activate', function (event) {
  console.log('--->activate14')
  var cacheAllowlist = [CACHE_NAME, 'blog-posts-cache-v1'];
  event.waitUntil(
    caches.keys().then(function (cacheNames) {
      return Promise.all(
        cacheNames.map(function (cacheName) {
          // console.log('delete', cacheName, cacheAllowlist.indexOf(cacheName))
          // if (cacheAllowlist.indexOf(cacheName) === -1) {
          return caches.delete(cacheName);
          // }
        })
      );
    }).then(function (cache) {
      return self.clients.matchAll().then(clients => {
        if (clients && clients.length) {
          clients.forEach(client => {
            // console.log('client---->',client)
            client.postMessage('sw.update')
          });
        }
      })
    })
  );
});

// self.addEventListener('fetch', event => {
//   const url = new URL(event.request.url);
//   console.log('fetch', event.request.url, url.origin, location.origin, url.pathname)

//   // serve the cat SVG from the cache if the request is
//   // same-origin and the path is '/svg1.svg'
//   if (url.origin == location.origin && url.pathname == '/image/svg1.svg') {
//     event.respondWith(caches.match('/image/svg2.svg'));
//   }
// });




self.addEventListener('fetch', function (event) {
  console.log('--->fetch')
  // console.log('fetch event',event) 
  event.respondWith(
    caches.match(event.request)
      .then(function (response) {
        // Cache hit - return response
        if (response) {
          console.log('response', response)
          return response;
        }



        var fetchRequest = event.request.clone();
        return fetch(fetchRequest).then(
          function (response) {
            // Check if we received a valid response
            if (!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT:Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            // 如果通过检查，则克隆响应。 这样做的原因在于，该响应是数据流， 
            // 因此主体只能使用一次。 由于我们想要返回能被浏览器使用的响应，并将其传递到缓存以供使用，
            // 因此需要克隆一份副本。我们将一份发送给浏览器，另一份则保留在缓存。
            var responseToCache = response.clone();
            // console.log(responseToCache) 

            caches.open(CACHE_NAME)
              .then(function (cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
  );
});